package com.IClass.IActivity;

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.IClass.IClassApi;
import com.IClass.NetUploadPictureListen;
import com.IClass.NetUtil;
import com.IClass.App.IClass;
import com.IClass.App.R;
import com.IClass.Server.AppJsonDefine.GenJavaCode.AppHttpHelp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.Toast;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;


public class ILookPicturesSwitchViewActivity extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory 
{

	public List<String> fileslist = new ArrayList<String>();
	public Map<String,Drawable> cachDrawable = new HashMap<String,Drawable>();
	public Map<String,Boolean> uploadimagethread = new HashMap<String,Boolean>();
	private ImageSwitcher mSwitcher;
	public Button btnpostupload;
	public Button btndeleteimagefile;
	public int selposition = 0;
	public TextView processtext;
	public Context context;
	
	public ProgressDialog progressDialog;
	public Handler mhandle = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.ilook_image_switch_layout);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));
        //processtext = (TextView) findViewById(R.id.processtext);
        String strImgPath = Environment.getExternalStorageDirectory().toString();
        strImgPath += "/ioclass/images/";
        File ioclassimagepath = new File(strImgPath);
        
        File files[] = ioclassimagepath.listFiles();
        for(File f:files)
        {
        	fileslist.add(f.getAbsolutePath());
        }
        
        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this,fileslist));
        g.setOnItemSelectedListener(this); 
        
        btnpostupload = (Button) findViewById(R.id.btnpostup);
        btndeleteimagefile = (Button) findViewById(R.id.btndeleteimage);
        context = this;
        btnpostupload.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
				SharedPreferences  share = context.getSharedPreferences("IClass", MODE_PRIVATE);  
		        String userid = share.getString("userid", "0");
		        
		        if(userid == "0")
		        {
					Intent mainIntent = new Intent(ILookPicturesSwitchViewActivity.this,IRegisterActivity.class); 
	                startActivity(mainIntent);    //启动Main界面
	                
		        	
		        }
		        else
		        {
		        	IClass.setUserid(userid);
		        	
		        	// FIXME Auto-generated method stub

					progressDialog = ProgressDialog.show(ILookPicturesSwitchViewActivity.this, "请稍等...","上传图片中...", true);
					uploadimagethread.put(fileslist.get(selposition), true);
					new Thread() {
						@Override
						public void run() 
						{
							// FIXME Auto-generated method stub
							NetUtil.UpLoadImage(IClassApi.SERVER_HOST+ AppHttpHelp.IdentificationPicture(IClass.getUserid()),fileslist.get(selposition), new NetUploadPictureListen() 
								{
	
											@Override
											public void OnResult(String result) 
											{
												// FIXME Auto-generated method stub
												Editor sharedata = getSharedPreferences("IClass", MODE_PRIVATE).edit();
												sharedata.putString("GetUploadlookpicture", "");
												sharedata.commit();
												IClass.getPictureresult().clear();
	
											}
	
								}
							);
							
							mhandle.post(new Runnable() 
							{
								@Override
								public void run() 
								{
									progressDialog.dismiss();
									Toast.makeText(ILookPicturesSwitchViewActivity.this, "上传图片成功", Toast.LENGTH_LONG).show();
								}

							});
							
						}

					}.start();
	        			
	        			
	        		
		        	
		        }
				
				
			}
			
		});
        btndeleteimagefile.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// FIXME Auto-generated method stub
				  
				File file = new File(fileslist.get(selposition));
				
				file.delete();
			}
			
		});
        
    }

    public void onItemSelected(AdapterView parent, View v, int position, long id) {
       //mSwitcher.setImageResource(mImageIds[position]);
    	selposition = position;
    	if(cachDrawable.get(this.fileslist.get(position)) != null)
    	{
    		Drawable drawable = cachDrawable.get(this.fileslist.get(position));
        	
        	mSwitcher.setImageDrawable(drawable);//(Uri.fromFile(new File(this.fileslist.get(position))));
    	}
    	else
    	{
    	  	BitmapFactory.Options options=new BitmapFactory.Options();
            options.inSampleSize = 2;
            
            
        	Drawable drawable = new BitmapDrawable(BitmapFactory.decodeFile(this.fileslist.get(position),options));
        	
        	mSwitcher.setImageDrawable(drawable);//(Uri.fromFile(new File(this.fileslist.get(position))));
        	cachDrawable.put(this.fileslist.get(position), drawable);
        	
    	}
  
    	
    	
    }
    
   
    public void onNothingSelected(AdapterView parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        return i;
    }

    

    public class ImageAdapter extends BaseAdapter {
    	private List<String> fileslist = null;
        public ImageAdapter(Context c,List<String> files) {
            mContext = c;
            this.fileslist = files;
        }

        public int getCount() {
            //return mThumbIds.length;
        	return fileslist.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            

            //Uri uri = Uri.fromFile(new File(this.fileslist.get(position)));
            //i.setImageURI(uri);
            if (convertView == null)
            {
            	
            	ImageView image = new ImageView(mContext);
            	BitmapFactory.Options options=new BitmapFactory.Options();
                options.inSampleSize = 10;
                image.setImageBitmap(BitmapFactory.decodeFile(this.fileslist.get(position),options));
                image.setAdjustViewBounds(true);
                image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                image.setBackgroundResource(R.drawable.picture_frame);
                convertView = image;
                return convertView;
            }

            return convertView;
        }

        private Context mContext;

    }

//    private Integer[] mThumbIds = {
//            R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
//            R.drawable.sample_thumb_2, R.drawable.sample_thumb_3,
//            R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
//            R.drawable.sample_thumb_6, R.drawable.sample_thumb_7};
//
//    private Integer[] mImageIds = {
//            R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
//            R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5,
//            R.drawable.sample_6, R.drawable.sample_7};

}
